package cj.utils;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Accuracy {
	static int total = 9; 
	static int scale = 1;
	public static void main(String[] args){
		int num = 3;  
          
        String result = accuracy(num, total, scale);  
        System.out.println(result);  
        //1%  
  
        num = 3;  
        result = accuracy(num, total, scale);  
        System.out.println(result);  
        //33.3%  
  
        num = 2;  
        result = accuracy(num, total, scale);  
        System.out.println(result);  
        //0.1%  
  
        num = 1;  
        result = accuracy(num, total, scale);  
        System.out.println(result);  
        //0%  
	}

	public static String accuracy(double num, double total, int scale) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		// 可以设置精确几位小数
		df.setMaximumFractionDigits(scale);
		// 模式 例如四舍五入
		df.setRoundingMode(RoundingMode.HALF_UP);
		double accuracy_num = num / total * 100;
		return df.format(accuracy_num) + "%";
	}
	
	public static String accuracy2(double num, double total, int scale) {
		//方法二  
        //0表示的是小数点  之前没有这样配置有问题例如  num=1 and total=1000  结果是.1  很郁闷  
        DecimalFormat df = new DecimalFormat("0%");  
        //可以设置精确几位小数  
        df.setMaximumFractionDigits(1);  
        //模式 例如四舍五入  
        df.setRoundingMode(RoundingMode.FLOOR);  
        double accuracy_num = num * 1.0/ total * 1.0;  
		return df.format(accuracy_num);   
	}
}
